package com.ktg.mes.md.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktg.common.core.domain.APIResult;
import com.ktg.common.utils.StringUtils;
import com.ktg.mes.md.domain.MdItem;
import com.ktg.mes.md.domain.MdStatistics;
import com.ktg.mes.md.service.IMdItemService;
import com.ktg.mes.md.service.IMdStatisticsService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.core.domain.Result;
import com.ktg.mes.md.domain.MdStatisticsTypeBom;
import com.ktg.mes.md.service.IMdStatisticsTypeBomService;
import com.ktg.common.utils.poi.ExcelUtil;

/**
 * 统计分类的统计分类BOMController
 *
 * @author byteco
 * @date 2023-02-22
 */
@RestController
@RequestMapping("/md/mdStatisticsTypeBom")
public class MdStatisticsTypeBomController extends BaseController
{
    @Autowired
    private IMdStatisticsTypeBomService mdStatisticsTypeBomService;

    @Autowired
    private IMdStatisticsService mdStatisticsService;

    @Autowired
    private IMdItemService mdItemService;

    /**
     * 查询统计分类的统计分类BOM列表
     */
    @PreAuthorize("@ss.hasPermi('md:mdStatisticsTypeBom:list')")
    @GetMapping("/list")
    public Result<IPage<MdStatisticsTypeBom>> list(MdStatisticsTypeBom mdStatisticsTypeBom,
                                            @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                            @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                            HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询统计分类的统计分类BOM列表",req,null);
        try {
            Page<MdStatisticsTypeBom> page = new Page<MdStatisticsTypeBom>(pageNo, pageSize);
            IPage<MdStatisticsTypeBom> pageList = mdStatisticsTypeBomService.queryPageList(mdStatisticsTypeBom,page);
            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 根据产品编号，查询统计分类的统计分类BOM列表
     */
    @GetMapping("/bomlist")
    public Result bomlist(@RequestParam(name="itemCode") String itemCode,
                                                   HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询统计分类的统计分类BOM列表",req,null);
        try {
            if (StringUtils.isEmpty(itemCode)){
               return apiLog.ok("产品编号 不能为空");
            }
            QueryWrapper wrapper = new QueryWrapper<>();
            wrapper.eq("item_code",itemCode);
            MdItem item = mdItemService.getOne(wrapper);
            if (item == null || item.getProcessProductId() == null){
                return apiLog.ok("找不到BOM数据");
            }

            QueryWrapper<MdStatisticsTypeBom> typeBomQueryWrapper = new QueryWrapper<>();
            typeBomQueryWrapper.eq("parent_id",item.getProcessProductId());
            List<MdStatisticsTypeBom> pageList = mdStatisticsTypeBomService.list(typeBomQueryWrapper);
            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 导出统计分类的统计分类BOM列表
     */
    @PreAuthorize("@ss.hasPermi('md:mdStatisticsTypeBom:export')")
    @Log(title = "统计分类的统计分类BOM", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MdStatisticsTypeBom mdStatisticsTypeBom,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("导出统计分类的统计分类BOM列表",req,mdStatisticsTypeBom);
        try {
            List<MdStatisticsTypeBom> list = mdStatisticsTypeBomService.queryList(mdStatisticsTypeBom);
            ExcelUtil<MdStatisticsTypeBom> util = new ExcelUtil<MdStatisticsTypeBom>(MdStatisticsTypeBom.class);
            util.exportExcel(response, list, "统计分类的统计分类BOM数据");
            apiLog.ok(null);
        }catch (Exception e){
            apiLog.error(e);
        }
    }

    /**
     * 获取统计分类的统计分类BOM详细信息
     */
    @PreAuthorize("@ss.hasPermi('md:mdStatisticsTypeBom:query')")
    @GetMapping(value = "/{bomId}")
    public Result<MdStatisticsTypeBom> getInfo(@PathVariable("bomId") Long bomId,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("获取统计分类的统计分类BOM详细信息",req,null);
        try {
            return apiLog.ok(mdStatisticsTypeBomService.getInfo(bomId));
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 新增统计分类的统计分类BOM
     */
    @PreAuthorize("@ss.hasPermi('md:mdStatisticsTypeBom:add')")
    @Log(title = "统计分类的统计分类BOM", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public Result<String> add(@RequestBody MdStatisticsTypeBom mdStatisticsTypeBom,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增统计分类的统计分类BOM",req,mdStatisticsTypeBom);
        try {
            MdStatisticsTypeBom ff = new MdStatisticsTypeBom();
            ff.setStatisticsId(mdStatisticsTypeBom.getStatisticsId());
            ff.setParentId(mdStatisticsTypeBom.getParentId());
            QueryWrapper<MdStatisticsTypeBom> queryWrapper = new QueryWrapper<>(ff);
            long a = mdStatisticsTypeBomService.count(queryWrapper);
            if (a > 0){
                return apiLog.fail("数据已存在");
            }
            MdStatistics mdStatistics = mdStatisticsService.getById(mdStatisticsTypeBom.getStatisticsId());
            mdStatisticsTypeBom.setStatisticsName(mdStatistics.getStatisticsName());
            mdStatisticsTypeBomService.insert(mdStatisticsTypeBom);
            mdStatisticsTypeBomService.updateStatisticsTypeBomString(mdStatisticsTypeBom.getParentId());
            return apiLog.ok("添加成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 修改统计分类的统计分类BOM
     */
    @PreAuthorize("@ss.hasPermi('md:mdStatisticsTypeBom:edit')")
    @Log(title = "统计分类的统计分类BOM", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public Result<String> edit(@RequestBody MdStatisticsTypeBom mdStatisticsTypeBom,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("修改统计分类的统计分类BOM",req,mdStatisticsTypeBom);
        try {
            MdStatistics mdStatistics = mdStatisticsService.getById(mdStatisticsTypeBom.getStatisticsId());
            mdStatisticsTypeBom.setStatisticsName(mdStatistics.getStatisticsName());
            mdStatisticsTypeBomService.update(mdStatisticsTypeBom);
            mdStatisticsTypeBomService.updateStatisticsTypeBomString(mdStatisticsTypeBom.getParentId());
            return apiLog.ok("编辑成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 删除统计分类的统计分类BOM
     */
    @PreAuthorize("@ss.hasPermi('md:mdStatisticsTypeBom:remove')")
    @Log(title = "统计分类的统计分类BOM", businessType = BusinessType.DELETE)
	@DeleteMapping("/{bomIds}")
    @Transactional
    public Result<String> remove(@PathVariable Long[] bomIds,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("删除统计分类的统计分类BOM",req,null);
        try {
            ArrayList<MdStatisticsTypeBom> bomArrayList = new ArrayList<>();
            for (int i = 0;i < bomIds.length;i++){
                MdStatisticsTypeBom bom = mdStatisticsTypeBomService.getById(bomIds[i]);
                bomArrayList.add(bom);
            }

            mdStatisticsTypeBomService.delete(bomIds);
            for (int i = 0;i < bomArrayList.size();i++){
                MdStatisticsTypeBom bom = bomArrayList.get(i);
                mdStatisticsTypeBomService.updateStatisticsTypeBomString(bom.getParentId());
            }
            return apiLog.ok("删除成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }

    }
}
